#include "compress.h"

Compress::Compress()
{

}

void Compress::SetPatFilePath(const QString &path)
{
    loadFilePath = path;
    qDebug()<<"loadFilePath"<<loadFilePath;
}

QString Compress::getStringBetween(const QString str, const QString start, const QString end)
{
    int startPos = str.indexOf(start);
    if (startPos == -1)
        return QString();

    startPos += start.length();
    int endPos = str.indexOf(end, startPos);
    if (endPos == -1)
        return QString();

    return str.mid(startPos, endPos - startPos);
}

QString Compress::getRearStr(const QString str, const QString mid)
{
    int index = str.indexOf(mid);
    if (index != -1)
    {
        QString substring = str.mid(index + mid.size());
        return substring;
    }
    else
        return "";
}

QString Compress::getFrontStr(const QString str, const QString mid)
{
    int index = str.indexOf(mid);
    if (index != -1)
    {
        QString substring = str.left(index);
        return substring;
    }
    else
        return "";
}

void Compress::writeFile(QTextStream &in, const QString l, const QString v, const QString c, const QString n)
{
    if(l.isEmpty())
        in << l << "\t\t\t" << v << ";";
    else if(l.toLower().startsWith("st:") || l.toLower() == "sp")
        in << l << "\t\t" << v << ";";
    else
        in << l << ":\t" << v << ";";
    if(!c.isEmpty())
    {
        in << c << "; ";
    }
    if(!n.isEmpty())
    {
        in << " //" << n;
    }
    in << "\n";
}

void Compress::ReadPatFile()
{
    //开始读取文件
    QFile patfile(loadFilePath);
    if (!patfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "文件打开失败！";
        return;
    }

    QFile infile("C:/Users/huabao/Desktop/1.txt");
    if (!infile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "文件打开失败！";
        return;
    }

    //用流去处理
    QTextStream loadPatFile(&patfile);
    QTextStream in(&infile);

    /*变量的位置*/
    QHash<int, QString> prefixData;
    QHash<int, QString> processedData;
    bool Get_Pattern = false;
    int lineNum = 1;
#define NOTE  "压缩注释"
    QString label="", vector="", cmd="", note="";
    //现在开始读取数据
    while(!loadPatFile.atEnd())
    {
        QString line = loadPatFile.readLine().trimmed();

        if (line.startsWith("START:") || line.startsWith("st:") || line.startsWith("ST:"))
        {
            Get_Pattern = true;
            label = "ST: ";
            vector = getStringBetween(line, ":", ";").trimmed();
            cmd = getStringBetween(line, ";", ";").trimmed();
            note = getRearStr(line, "//");
            //qDebug() << vector << " " << cmd << " " << note;
            //in << "@@PATTERN_DEFINE\n";

            writeFile(in, label, vector, cmd, note);
            /*
            in << label << "  " << vector << "; " << cmd << "; ";
            if(!note.isEmpty())
            {
                in << "//" << note;
            }
            in << "\n";*/

            lineNum = 1;
            vector.clear();
            cmd.clear();
            note.clear();
            label.clear();
        }
        else
        {
            if(Get_Pattern)
            {
                QString label_t = getFrontStr(line, ":").trimmed();
                QString vector_t = getFrontStr(line, ";").trimmed();
                if(vector_t.contains(":"))
                    vector_t = getRearStr(vector_t, ":").trimmed();
                QString cmd_t = getRearStr(line, ";").trimmed();
                if(cmd_t.contains("//"))
                {
                    cmd_t = getFrontStr(cmd_t, "//").trimmed();
                    if(cmd_t.startsWith("/"))
                    {
                        cmd_t = "";
                    }
                }
                if(cmd_t.endsWith(";"))
                    cmd_t.chop(1);
                QString note_t = getRearStr(line, "//").trimmed();
#if 1
                qDebug() << "*****************";
                qDebug() << line;
                qDebug() << "label=" << label << " vector=" << vector << " cmd=" << cmd << " note=" << note << " lineNum=" << lineNum;
                qDebug() << "label_t=" << label_t << " vector_t=" << vector_t << " cmd_t=" << cmd_t << " note_t=" << note_t;
                qDebug() << "^^^^^^^^^^^^^^^^^^^^";
#endif
                if (line.toUpper().startsWith("EXIT:") || line.toUpper().startsWith("SP:")|| line.toUpper().startsWith("STOP:"))
                {
                    QString label_t = "SP: ";
                    if(lineNum > 1)
                    {
                        if(!cmd.isEmpty())
                        {
                            cmd += " RTP " +  QString::number(lineNum);
                        }
                        else
                        {
                            vector += "; RTP " +  QString::number(lineNum);
                        }
                        writeFile(in, label, vector, cmd, note);
                    }
                    else if(!vector.isEmpty())
                        writeFile(in, label, vector, cmd, note);

                    vector_t = getStringBetween(line, ":", ";").trimmed();
                    if(cmd_t.isEmpty())
                    {
                        in << label_t << "\t\t" << vector_t;
                    }
                    else
                    {
                        in << label_t << "\t\t" << vector_t << "; " << cmd_t << "; ";
                    }

                    if(!note_t.isEmpty())
                    {
                        in << "//" << note_t;
                    }
                    in << "\n";

                    in << "@@END_PATTERN_DEFINE\n";
                    vector.clear();
                    cmd.clear();
                    note.clear();
                    label.clear();

                    patfile.close();
                    infile.close();
                    break;
                }
                else if(cmd_t.toLower().contains("host") \
                    || cmd_t.toLower().contains("capture")\
                    || cmd_t.toLower().contains("loop")\
                    || cmd_t.toLower().contains("cont"))
                {
                    //qDebug() << vector << " " << lineNum << " cmd=" << cmd;
                    if(lineNum > 1)
                    {
                        if(!cmd.isEmpty())
                        {
                            cmd += " RTP " +  QString::number(lineNum);
                        }
                        else
                        {
                            vector += "; RTP " +  QString::number(lineNum);
                        }
                        writeFile(in, label, vector, cmd, note);
                    }
                    else if(!vector.isEmpty())
                        writeFile(in, label, vector, cmd, note);
                    writeFile(in, label_t, vector_t, cmd_t, note_t);

                    lineNum = 1;
                    vector.clear();
                    cmd.clear();
                    note.clear();
                    label.clear();
                }
                else if(vector_t == vector)
                {
                    //qDebug() << vector_t << " cmd:" << cmd << " cmd_t:" << cmd_t;
                    if(cmd_t == cmd || cmd_t.isEmpty())
                    {
                        //label不同
                        if(label != label_t && !label_t.isEmpty())
                        {
                            if(lineNum > 1)
                            {
                                if(!cmd.isEmpty())
                                {
                                    cmd += " RTP " +  QString::number(lineNum);
                                }
                                else
                                {
                                    vector += "; RTP " +  QString::number(lineNum);
                                }
                                writeFile(in, label, vector, cmd, note);

                                lineNum = 1;
                            }
                            else
                            {
                                writeFile(in, label, vector, cmd, note);
                            }

                            vector = vector_t;
                            label = label_t;
                            cmd = cmd_t;
                            note = note_t;
                        }
                        else
                        {
                            lineNum++;

                            //if(cmd.isEmpty())
                            //    cmd = cmd_t;

                            if(!note.isEmpty())
                            {
                                if(!note_t.isEmpty())
                                {
                                    if(note != note_t)
                                        note = NOTE;
                                }
                            }
                            else
                            {
                                if(!note_t.isEmpty())
                                    note = note_t;
                            }

                            //max = 2;
                            if(lineNum >= max)//限制
                            {
                                if(!cmd.isEmpty())
                                {
                                    cmd += " RTP " +  QString::number(lineNum);
                                }
                                else
                                {
                                    vector += "; RTP " +  QString::number(lineNum);
                                }
                                writeFile(in, label, vector, cmd, note);

                                lineNum = 1;
                                vector.clear();
                                cmd.clear();
                                note.clear();
                                label.clear();
                            }
                        }
                    }
                    else
                    {
                        //cmd不同
                        if(lineNum > 1)
                        {
                            if(!cmd.isEmpty())
                            {
                                cmd += " RTP " +  QString::number(lineNum);
                            }
                            else
                            {
                                vector += "; RTP " +  QString::number(lineNum);
                            }
                            writeFile(in, label, vector, cmd, note);

                            lineNum = 1;
                        }
                        else
                        {
                            writeFile(in, label, vector, cmd, note);
                        }

                        vector = vector_t;
                        label = label_t;
                        cmd = cmd_t;
                        note = note_t;
                    }
                }
                else if(!vector.isEmpty())//vector不同
                {
                    if(lineNum > 1)
                    {
                        if(!cmd.isEmpty())
                        {
                            cmd += " RTP " +  QString::number(lineNum);
                        }
                        else
                        {
                            vector += "; RTP " +  QString::number(lineNum);
                        }
                        writeFile(in, label, vector, cmd, note);
                    }
                    else
                        writeFile(in, label, vector, cmd, note);

                    lineNum = 1;
                    vector = vector_t;
                    label = label_t;
                    cmd = cmd_t;
                    note = note_t;
                }
                else
                {
                    vector = vector_t;
                    label = label_t;
                    cmd = cmd_t;
                    note = note_t;
                }
            }
            else
            {
                if(!line.isEmpty())
                {
                    in << line << "\n";
                }
            }
        }
        //qDebug() << "^^^^^^^^^^^^^^^^^";
    }
    infile.close();
    patfile.close();
    qDebug() << "end";
#if 0
        QString line = loadPatFile.readLine().trimmed();
        lineNum++;

        if(line.startsWith("START:"))
        {
            Get_Pattern = true;
            //continue;
        }
        if(line.contains("STOP"))
        {
            Get_Pattern = false;
            break;
        }


        if(Get_Pattern)
        {
            //现在应该截取lable vector 微指令三个部分
            /*label*/
            QString prefix;
            if (line.startsWith("START:") || line.startsWith("st:") || line.startsWith("ST:"))
            {
                prefix = "ST: ";
            }
            else if (line.startsWith("EXIT:") || line.startsWith("sp:")|| line.startsWith("SP:"))
            {
                prefix = "SP: ";
            }
            else
            {
                prefix = "\t"; //前缀
            }
            prefixData[lineNum] = prefix;  // 为当前行保存prefix

            /*Vector*/
            if (!line.trimmed().startsWith("//"))
            {
                if (line.contains(";")) {
                    QString extractedData;

                    if (line.contains(":")) {
                        // 使用正则表达式从line中提取所需数据
                        QRegularExpression regex(":\\s*(.*?)\\s*;");
                        QRegularExpressionMatch match = regex.match(line);
                        if (match.hasMatch()) {
                            extractedData = match.captured(1);
                        }
                    } else {
                        // 获取直到第一个分号的内容
                        extractedData = line.split(";").first().trimmed();
                    }

                    if (!extractedData.isEmpty()) {
                        lineVector.append(extractedData);
                        processedData[lineNum] = extractedData;
                    }
                }
            }

            /*------------------------------现在截取微指令的部分的部分---------------------------------------*/
            if (!line.trimmed().startsWith("//")) { //获取注释
                if (line.contains("//") ) {
                    int index;
                    QString endData;  // 用于存储分割后的内容
                    for(int i=0; i<keywords.size(); ++i) {
                        QString keyword = keywords.at(i);
                        if (line.contains(keyword)) {
                            index = line.indexOf(keyword); //要切割的东西
                            endData = line.mid(index);
                            QString data = endData.split(";").first();
                            AC_SET[lineNum] = data;
                            endData.replace(data+";","");//更新endData
                        }
                        else {
                            index = line.indexOf("//");
                            endData = line.mid(index);
                        }
                    }
                    commentData[lineNum] = endData.trimmed();
                }
            }
        }
    }
#endif

#if 0
    qDebug()<<"lineVector"<<lineVector;
    qDebug()<<"processedData"<<processedData;
    qDebug()<<"prefixData"<<prefixData;
    qDebug()<<"ac_aet"<<AC_SET;
    qDebug()<<"commData"<<commentData;
#endif
}

int Compress::getMax() const
{
    return max;
}

void Compress::setMax(int newMax)
{
    max = newMax;
}
